package com.david.cms.controller;
import com.sun.image.codec.jpeg.JPEGCodec;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.util.upload.ServletFileUpload;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.david.basic.model.Pager;
import com.david.cms.channel.service.IChannelDetailsService;
import com.david.cms.channel.service.IChannelService;
import com.david.cms.model.Channel;
import com.david.cms.model.ChannelDetails;
@RequestMapping("/admin/channeldetails_manage")
@Controller
public class ChannelDetailsManageController {
	private IChannelDetailsService channelDetailsService;

	@Inject
	public void setChannelDetailsService(
			IChannelDetailsService channelDetailsService) {
		this.channelDetailsService = channelDetailsService;
	}

	private IChannelService channelService;

	public IChannelService getChannelService() {
		return channelService;
	}
	@Inject
	public void setChannelService(IChannelService channelService) {
		this.channelService = channelService;
	}
	

	//分页展示
	@RequestMapping(value = "initPage")
	public ModelAndView tomange(Model model){
		System.out.println("进来啦！！！！！！！！！");
		Pager<ChannelDetails> datas=channelDetailsService.getPager();
		model.addAttribute("datas",datas);
		return new ModelAndView("channel/channeldetails_list");
	}
	
	//跳转至添加
		@RequestMapping(value = "toAdd")
		public ModelAndView toAdd(Model model){
			model.addAttribute("channel",this.channelService.getTopChannel());
			return new ModelAndView("channel/add_channelDetails");
		}
		//添加
		@RequestMapping(value = "add")
		public ModelAndView add(ChannelDetails c){
		c.setChannelDetailsCreateDate(new Date());
		c.setChannelDetailsCreateName("psps");
		
		if(!(c.getChannelDetailsPic()=="null")&&c.getChannelDetailsPic().length()>0){
			
			File file=new File(c.getChannelDetailsPic());
			String url=ysImg(file);
			c.setChannelDetailsPic(url);
			System.out.println(url.length()+"--------");
		}
		System.out.println(c.getChannelDetailsContent()+"----------------------");
		channelDetailsService.add(c);
		return new ModelAndView("redirect:/admin/channeldetails_manage/initPage");
		}
		//跳转至修改
		@RequestMapping(value = "toUpdate/{id}")
		public ModelAndView toUpdate(@PathVariable String id,Model model){
		model.addAttribute("channel",channelService.getTopChannel());
		ChannelDetails cd=channelDetailsService.getOne(Long.valueOf(id));
		model.addAttribute("cd",cd);
		model.addAttribute("channelchild",channelService.generateTreeByParent(cd.getChannel().getParent().getId()));
		return new ModelAndView("channel/update_channelDetails");
		}
		//添加
		@RequestMapping(value = "update")
		public ModelAndView update(ChannelDetails c,String channelDetailsCreateDate2) throws ParseException{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			c.setChannelDetailsCreateDate(sdf.parse(channelDetailsCreateDate2));
			
			if(!(c.getChannelDetailsPic()=="null")&&c.getChannelDetailsPic().length()>0){
				
				
				File file=new File(c.getChannelDetailsPic());
				String url=ysImg(file);
				c.setChannelDetailsPic(url);
				System.out.println(url.length()+"--------");
			}
		channelDetailsService.update(c);
		return new ModelAndView("redirect:/admin/channeldetails_manage/initPage");
			}	
		
		//跳转至查看
				@RequestMapping(value = "show/{id}")
				public ModelAndView show(@PathVariable String id,Model model){
				model.addAttribute("cd", channelDetailsService.getOne(Long.valueOf(id)));
				return new ModelAndView("channel/show_channelDetails");
				}
				//删除
				@RequestMapping(value = "delete/{id}")
				public ModelAndView delete(@PathVariable String id,Model model){
				channelDetailsService.delete(Long.valueOf(id));
				return new ModelAndView("redirect:/admin/channeldetails_manage/initPage");
				}
				
				//通过channelid得到zi目录
				@RequestMapping(value = "getChannelSub/{id}")
				public void getChannelSub(@PathVariable String id,Model model,HttpServletRequest request, HttpServletResponse response) throws IOException{
			
					 response.setContentType("text/xml;charset=utf-8");
			          request.setCharacterEncoding("utf-8");
			          response.setCharacterEncoding("utf-8");
					List<Channel>	list=this.channelService.listByParent(Integer.valueOf(id));
					if(list==null){
						
						response.getWriter().println("<option value='-1'>没有子目录</option>");
					}else{
						
						for(int i=0;i<list.size();i++){
							response.getWriter().println("<option value='"+list.get(i).getId()+"'>"+list.get(i).getName()+"</option>");
							
						}
						
						
						
					}
			
				}
				
				public String ysImg(File f){
					 int newWidth; int newHeight; 
					 String hz=f.getName().substring(f.getName().lastIndexOf(".")+1,f.getName().length());
					 String outName="";
					try {
						String newDir="D:/eclipse_workplace/cms-web/src/main/webapp/resources/fileupload/";
						Image img = ImageIO.read(f); 
						 double rate1 = ((double) img.getWidth(null));
		                 double rate2 = ((double) img.getHeight(null)); 
		                 // 根据缩放比率大的进行缩放控制   
		                 double rate = rate1 > rate2 ? rate1 : rate2;   
//		                 newWidth = (double) img.getWidth(null)) / rate);   
//		                 newHeight = (int) (((double) img.getHeight(null)) / rate);  
		                 
//		                 System.out.println(newWidth+"-------------"+newHeight);
		                 
		                 BufferedImage tag = new BufferedImage((int) rate1, (int) rate2, BufferedImage.TYPE_INT_RGB);   
		                 /* 
		                  * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 
		                  * 优先级比速度高 生成的图片质量比较好 但速度慢 
		                  */   
		                 
		                 outName=UUID.randomUUID().toString().replace("-","")+"."+hz;
		                 tag.getGraphics().drawImage(img.getScaledInstance(img.getWidth(null), img.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);  
		                 FileOutputStream out = new FileOutputStream(newDir+outName);  
		                 // JPEGImageEncoder可适用于其他图片类型的转换   
		                 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);              		   
		                 encoder.encode(tag);   
		                 out.close();   
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					return outName;
				}
}
